package com.swak.persistence.mybatis.methods.impls;

import com.swak.define.ColumnDefine;
import com.swak.persistence.mybatis.methods.Sqls;
import com.swak.utils.StringUtils;

/**
 * 更新
 * 
 * @author lifeng
 * @date 2021年1月25日 下午5:13:45
 */
public class Updative extends QueryByCondition {

	@Override
	protected void doInject() {
		if (!this.supportMethod(Sqls.UPDATIVE)) {
			return;
		}

		String sql = new StringBuilder().append(SCRIPT_START).append(UPDATE).append(SPACE).append(this.table.getName())
				.append(SPACE).append(this.convertSet(this.parseUpdateProperty())).append(SPACE)
				.append(this.parseWhereLogicDelEqualColumn(false)).append(this.parseUpdativeEqualColumns())
				.append(SPACE).append(this.parseOptimismLockCheckColumn()).append(SCRIPT_END).toString();

		this.addUpdateMappedStatement(Sqls.UPDATIVE.getMethod(), sql);
	}

	protected String convertSet(String sql) {
		return SET_START + sql + SET_END;
	}

	protected String parseOptimismLockCheckColumn() {
		if (this.table.define.useOptimismLock()) {
			return OP_LOCK_CHECK;
		}
		return StringUtils.EMPTY;
	}

	/**
	 * 解析修改列
	 */
	protected String parseUpdateProperty() {
		StringBuilder sql = new StringBuilder();
		sql.append(Updative.includeUpdativeColumns());
		if (this.table.define.useOptimismLock()) {
			sql.append(SPLIT).append(OP_LOCK_ADD);
		}
		return sql.toString();
	}

	protected String parseUpdativeEqualColumns() {
		StringBuilder sql = new StringBuilder();
		sql.append(QueryByCondition.includeConditionClause());
		sql.append("<if test=\"!valid\">");
		sql.append(LEFT_BRACKET).append(PADDING).append(SPACE);
		for (ColumnDefine column : table.getColumns()) {
			if (!column.isVersion()) {
				sql.append("<if test=\"").append(MODEL).append(DOT).append(column.javaProperty).append(" != null\">");
				sql.append(AND).append(column.name).append(EQUALS).append(HASH_LEFT_BRACE).append(MODEL).append(DOT)
						.append(column.javaPropertyEl).append(RIGHT_BRACE);
				sql.append("</if>");
			}
		}
		sql.append(RIGHT_BRACKET);
		sql.append("</if>");
		return sql.toString();
	}
}